/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package api;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
import com.sun.xml.wss.impl.misc.Base64;
import entity.Article;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

/**
 *
 * @author remi
 */
@Stateless
@Path("/article")
public class ArticleFacadeREST extends AbstractFacade<Article> {

    @PersistenceContext(unitName = "BlogWSPU")
    private EntityManager em;
    private static int imageSansTitre = 0;

    public ArticleFacadeREST() {
        super(Article.class);
    }

    @POST
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public String create(@FormDataParam("titre") String titre,
            @FormDataParam("content") String content,
            @FormDataParam("image0") InputStream uploadedInputStream,
            @FormDataParam("image0") FormDataContentDisposition fileDetail) throws IOException {
        System.out.println("Titre : " + titre + "\ncontent : " + content + "\nStream" + uploadedInputStream + "\nDetail" + fileDetail);
        //create article
        Article a = new Article(titre, content);
        String filename = "";
        //Create directory
        try {
            String strDirectoy = "images";
            boolean success = (new File(strDirectoy)).mkdir();
            if (success) {
                System.out.println("Directory: "
                        + strDirectoy + " created");
            } else {
                System.out.println("Le dossier existe déjà :");
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }

        //si un fichier a été envoyer, l'uploader sur le serveur et ajouter a l'article
        if (uploadedInputStream != null) {
            try {
                File f;
                if (fileDetail.getFileName() != null) {
                    filename = fileDetail.getFileName();
                    f = new File("images/" + fileDetail.getFileName());
                    OutputStream out = new FileOutputStream(f);
                    byte buf[] = new byte[1024];
                    int len;
                    while ((len = uploadedInputStream.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.close();
                } else {
                    filename = "image"+ imageSansTitre + ".png";
                    f = new File("images/"+filename);
                    String buffer = "";
                    byte buf[] = new byte[1024];
                    int len;
                    while ((len = uploadedInputStream.read(buf)) > 0) {
                        buffer += new String(buf);
                    }
                    //System.out.println("Canvas : "+buffer.toString());
                    String[] res = buffer.split(",");
                    byte[] btDataFile = new sun.misc.BASE64Decoder().decodeBuffer(res[1]);
                    FileOutputStream osf = new FileOutputStream(f);
                    osf.write(btDataFile);
                    osf.flush();
                    osf.close();
                    imageSansTitre++;
                }
                //System.out.println(f.getAbsolutePath());

                uploadedInputStream.close();
            } catch (FileNotFoundException e) {
                System.out.println("Error funtion create / creating file\n");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("Error IOE\n");
                e.printStackTrace();
            }
            //add URL picture's at database
            a.setImage(filename);
        }
        super.create(a);
        return "/BlogWS_Version_Test/resources/article/"+a.getId();
    }

    @PUT
    @Consumes({MediaType.APPLICATION_FORM_URLENCODED, "application/json"})
    public Article edit(MultivaluedMap<String, String> inFormParams) {
        Article a = super.find(Long.parseLong(inFormParams.getFirst("id")));
        a.setContent(inFormParams.getFirst("content"));
        a.setTitre(inFormParams.getFirst("titre"));
        super.edit(a);
        return a;
    }

    @DELETE
    @Path("{id}")
    public String remove(@PathParam("id") Long id) {
        super.remove(super.find(id));
        return "" + id;
    }

    @GET
    @Path("{id}")
    @Produces({"application/json"})
    public Article find(@PathParam("id") Long id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({"application/json"})
    public List<Article> findAll() {
        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({"application/xml", "application/json"})
    public List<Article> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        int[] range = new int[]{from, to};
        Query q = em.createQuery("select a from Article a ORDER BY a.time ASC", Article.class);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        List<Article> result = q.getResultList();
        /**
         * ArrayList<Article> tmps = new ArrayList(); try { for (Article a :
         * result) { //Conversion de l'image en data url
         * //data:image/extension;base64,<dataInBase64> String dataurl =
         * "data:image/" + a.getExtension() + ";"; File file = new
         * File("./images/" + a.getImage()); FileInputStream in = new
         * FileInputStream(file); byte fileContent[] = new byte[(int)
         * file.length()]; in.read(fileContent); String s =
         * Base64.encode(fileContent); System.out.println("Data send !!");
         * dataurl = dataurl+"base64,"+s; a.setImage(dataurl); in.close(); } }
         * catch (Exception e) { System.out.println("Erreur lors de l'envoi de
         * l'image"); e.printStackTrace(); }
         *
         */
        return result;
    }

    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }

    @java.lang.Override
    protected EntityManager getEntityManager() {
        return em;
    }
}
